import { Request, Response } from 'express';
import { UserService } from '../services/userService';
import { asyncHandler } from '../utils/asyncHandler';
import { AppError } from '../utils/errors';
import { successResponse } from '../utils/response';
import logger from '../utils/logger';
import { 
  CreateUserRequest, 
  UpdateUserRequest, 
  UserQueryParams,
  CreateUserAddressRequest,
  UpdateUserAddressRequest,
  AddressQueryParams
} from '../types/user';

/**
 * @swagger
 * components:
 *   schemas:
 *     User:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 用户ID
 *         username:
 *           type: string
 *           description: 用户名
 *         email:
 *           type: string
 *           description: 邮箱
 *         phone:
 *           type: string
 *           description: 手机号
 *         avatar:
 *           type: string
 *           description: 头像URL
 *         nickname:
 *           type: string
 *           description: 昵称
 *         gender:
 *           type: integer
 *           enum: [0, 1, 2]
 *           description: 性别：0-未知，1-男，2-女
 *         genderText:
 *           type: string
 *           description: 性别文本
 *         birthday:
 *           type: string
 *           format: date
 *           description: 生日
 *         status:
 *           type: integer
 *           enum: [0, 1]
 *           description: 状态：0-禁用，1-正常
 *         statusText:
 *           type: string
 *           description: 状态文本
 *         levelId:
 *           type: integer
 *           description: 会员等级ID
 *         points:
 *           type: integer
 *           description: 积分
 *         balance:
 *           type: number
 *           description: 账户余额
 *         lastLoginAt:
 *           type: string
 *           format: date-time
 *           description: 最后登录时间
 *         createdAt:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         updatedAt:
 *           type: string
 *           format: date-time
 *           description: 更新时间
 *     
 *     UserAddress:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 地址ID
 *         userId:
 *           type: integer
 *           description: 用户ID
 *         receiverName:
 *           type: string
 *           description: 收货人姓名
 *         receiverPhone:
 *           type: string
 *           description: 收货人电话
 *         province:
 *           type: string
 *           description: 省份
 *         city:
 *           type: string
 *           description: 城市
 *         district:
 *           type: string
 *           description: 区县
 *         address:
 *           type: string
 *           description: 详细地址
 *         fullAddress:
 *           type: string
 *           description: 完整地址
 *         postalCode:
 *           type: string
 *           description: 邮政编码
 *         isDefault:
 *           type: integer
 *           enum: [0, 1]
 *           description: 是否默认地址：0-否，1-是
 *         isDefaultText:
 *           type: string
 *           description: 默认地址文本
 *         createdAt:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         updatedAt:
 *           type: string
 *           format: date-time
 *           description: 更新时间
 */

export class UserController {
  private userService: UserService;

  constructor() {
    this.userService = new UserService();
  }

  /**
   * @swagger
   * /api/users:
   *   post:
   *     summary: 创建用户
   *     tags: [用户管理]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - username
   *               - email
   *               - password
   *             properties:
   *               username:
   *                 type: string
   *                 description: 用户名
   *               email:
   *                 type: string
   *                 description: 邮箱
   *               password:
   *                 type: string
   *                 description: 密码
   *               phone:
   *                 type: string
   *                 description: 手机号
   *               nickname:
   *                 type: string
   *                 description: 昵称
   *               gender:
   *                 type: integer
   *                 enum: [0, 1, 2]
   *                 description: 性别
   *               birthday:
   *                 type: string
   *                 format: date
   *                 description: 生日
   *     responses:
   *       201:
   *         description: 用户创建成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   $ref: '#/components/schemas/User'
   */
  createUser = asyncHandler(async (req: Request, res: Response) => {
    const userData: CreateUserRequest = req.body;
    
    // 基本验证
    if (!userData.username || !userData.email || !userData.password) {
      throw new AppError('用户名、邮箱和密码为必填项', 400);
    }

    if (userData.password.length < 6) {
      throw new AppError('密码长度不能少于6位', 400);
    }

    const user = await this.userService.createUser(userData);

    return successResponse(res, user, '用户创建成功', 200);
  });

  /**
   * @swagger
   * /api/users:
   *   get:
   *     summary: 获取用户列表
   *     tags: [用户管理]
   *     parameters:
   *       - in: query
   *         name: page
   *         schema:
   *           type: integer
   *           default: 1
   *         description: 页码
   *       - in: query
   *         name: limit
   *         schema:
   *           type: integer
   *           default: 10
   *         description: 每页数量
   *       - in: query
   *         name: keyword
   *         schema:
   *           type: string
   *         description: 搜索关键词
   *       - in: query
   *         name: status
   *         schema:
   *           type: integer
   *           enum: [0, 1]
   *         description: 用户状态
   *       - in: query
   *         name: gender
   *         schema:
   *           type: integer
   *           enum: [0, 1, 2]
   *         description: 性别
   *       - in: query
   *         name: levelId
   *         schema:
   *           type: integer
   *         description: 会员等级ID
   *       - in: query
   *         name: startDate
   *         schema:
   *           type: string
   *           format: date
   *         description: 开始日期
   *       - in: query
   *         name: endDate
   *         schema:
   *           type: string
   *           format: date
   *         description: 结束日期
   *       - in: query
   *         name: sortBy
   *         schema:
   *           type: string
   *           enum: [id, username, email, createdAt, lastLoginAt, points, balance]
   *           default: id
   *         description: 排序字段
   *       - in: query
   *         name: sortOrder
   *         schema:
   *           type: string
   *           enum: [ASC, DESC]
   *           default: DESC
   *         description: 排序方向
   *     responses:
   *       200:
   *         description: 获取用户列表成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   type: object
   *                   properties:
   *                     users:
   *                       type: array
   *                       items:
   *                         $ref: '#/components/schemas/User'
   *                     pagination:
   *                       type: object
   *                       properties:
   *                         page:
   *                           type: integer
   *                         limit:
   *                           type: integer
   *                         total:
   *                           type: integer
   *                         totalPages:
   *                           type: integer
   */
  getUserList = asyncHandler(async (req: Request, res: Response) => {
    // 处理可能嵌套在params中的查询参数
    const queryParams = req.query.params ? req.query.params as any : req.query;
    
    const params: UserQueryParams = {
      page: parseInt(queryParams.page as string) || 1,
      limit: parseInt(queryParams.limit as string) || 10,
      keyword: queryParams.keyword as string,
      status: queryParams.status && queryParams.status !== '' ? parseInt(queryParams.status as string) as 0 | 1 : undefined,
      gender: queryParams.gender && queryParams.gender !== '' ? parseInt(queryParams.gender as string) as 0 | 1 | 2 : undefined,
      levelId: queryParams.levelId ? parseInt(queryParams.levelId as string) : undefined,
      startDate: queryParams.startDate as string,
      endDate: queryParams.endDate as string,
      sortBy: queryParams.sortBy as any || 'id',
      sortOrder: queryParams.sortOrder as 'ASC' | 'DESC' || 'DESC'
    };

    const result = await this.userService.getUserList(params);

    return successResponse(res, result, '获取用户列表成功');
  });

  /**
   * @swagger
   * /api/users/{id}:
   *   get:
   *     summary: 获取用户详情
   *     tags: [用户管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *     responses:
   *       200:
   *         description: 获取用户详情成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   $ref: '#/components/schemas/User'
   */
  getUserById = asyncHandler(async (req: Request, res: Response) => {
    const id = parseInt(req.params.id);
    
    if (isNaN(id)) {
      throw new AppError('无效的用户ID', 400);
    }

    const user = await this.userService.getUserById(id);

    return successResponse(res, user, '获取用户详情成功');
  });

  /**
   * @swagger
   * /api/users/{id}:
   *   put:
   *     summary: 更新用户
   *     tags: [用户管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             properties:
   *               username:
   *                 type: string
   *               email:
   *                 type: string
   *               phone:
   *                 type: string
   *               nickname:
   *                 type: string
   *               gender:
   *                 type: integer
   *                 enum: [0, 1, 2]
   *               birthday:
   *                 type: string
   *                 format: date
   *               avatar:
   *                 type: string
   *               status:
   *                 type: integer
   *                 enum: [0, 1]
   *               levelId:
   *                 type: integer
   *               points:
   *                 type: integer
   *               balance:
   *                 type: number
   *     responses:
   *       200:
   *         description: 用户更新成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   $ref: '#/components/schemas/User'
   */
  updateUser = asyncHandler(async (req: Request, res: Response) => {
    const id = parseInt(req.params.id);
    const updateData: UpdateUserRequest = req.body;
    
    if (isNaN(id)) {
      throw new AppError('无效的用户ID', 400);
    }

    const user = await this.userService.updateUser(id, updateData);

    return successResponse(res, user, '用户更新成功');
  });

  /**
   * @swagger
   * /api/users/{id}:
   *   delete:
   *     summary: 删除用户
   *     tags: [用户管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *     responses:
   *       200:
   *         description: 用户删除成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   */
  deleteUser = asyncHandler(async (req: Request, res: Response) => {
    const id = parseInt(req.params.id);
    
    if (isNaN(id)) {
      throw new AppError('无效的用户ID', 400);
    }

    await this.userService.deleteUser(id);

    return successResponse(res, null, '用户删除成功');
  });

  /**
   * @swagger
   * /api/users/batch-delete:
   *   post:
   *     summary: 批量删除用户
   *     tags: [用户管理]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - ids
   *             properties:
   *               ids:
   *                 type: array
   *                 items:
   *                   type: integer
   *                 description: 用户ID数组
   *     responses:
   *       200:
   *         description: 批量删除成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   */
  batchDeleteUsers = asyncHandler(async (req: Request, res: Response) => {
    const { ids } = req.body;
    
    if (!Array.isArray(ids) || ids.length === 0) {
      throw new AppError('请提供要删除的用户ID列表', 400);
    }

    await this.userService.batchDeleteUsers(ids);

    return successResponse(res, null, `成功删除 ${ids.length} 个用户`);
  });

  /**
   * @swagger
   * /api/users/{id}/status:
   *   patch:
   *     summary: 更新用户状态
   *     tags: [用户管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - status
   *             properties:
   *               status:
   *                 type: integer
   *                 enum: [0, 1]
   *                 description: 用户状态：0-禁用，1-正常
   *     responses:
   *       200:
   *         description: 用户状态更新成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   $ref: '#/components/schemas/User'
   */
  updateUserStatus = asyncHandler(async (req: Request, res: Response) => {
    const id = parseInt(req.params.id);
    const { status } = req.body;
    
    if (isNaN(id)) {
      throw new AppError('无效的用户ID', 400);
    }

    if (![0, 1].includes(status)) {
      throw new AppError('状态值必须为0或1', 400);
    }

    const user = await this.userService.updateUserStatus(id, status);

    return successResponse(res, user, '用户状态更新成功');
  });

  /**
   * @swagger
   * /users/stats:
   *   get:
   *     summary: 获取用户统计信息
   *     tags: [用户管理]
   *     responses:
   *       200:
   *         description: 获取用户统计信息成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   type: object
   *                   properties:
   *                     totalUsers:
   *                       type: integer
   *                       description: 总用户数
   *                     activeUsers:
   *                       type: integer
   *                       description: 活跃用户数
   *                     inactiveUsers:
   *                       type: integer
   *                       description: 禁用用户数
   *                     newUsersToday:
   *                       type: integer
   *                       description: 今日新增用户
   *                     newUsersThisWeek:
   *                       type: integer
   *                       description: 本周新增用户
   *                     newUsersThisMonth:
   *                       type: integer
   *                       description: 本月新增用户
   *                     genderDistribution:
   *                       type: object
   *                       properties:
   *                         unknown:
   *                           type: integer
   *                         male:
   *                           type: integer
   *                         female:
   *                           type: integer
   *                     levelDistribution:
   *                       type: object
   *                       additionalProperties:
   *                         type: integer
   */
  getUserStats = asyncHandler(async (req: Request, res: Response) => {
    const stats = await this.userService.getUserStats();

    return successResponse(res, stats, '获取用户统计信息成功');
  });

  // 用户地址相关接口
  /**
   * @swagger
   * /addresses:
   *   get:
   *     summary: 获取所有用户地址列表（管理员）
   *     tags: [用户地址管理]
   *     parameters:
   *       - in: query
   *         name: page
   *         schema:
   *           type: integer
   *           default: 1
   *         description: 页码
   *       - in: query
   *         name: pageSize
   *         schema:
   *           type: integer
   *           default: 10
   *         description: 每页数量
   *       - in: query
   *         name: userId
   *         schema:
   *           type: string
   *         description: 用户ID筛选
   *       - in: query
   *         name: receiverName
   *         schema:
   *           type: string
   *         description: 收货人姓名筛选
   *       - in: query
   *         name: receiverPhone
   *         schema:
   *           type: string
   *         description: 收货人电话筛选
   *       - in: query
   *         name: province
   *         schema:
   *           type: string
   *         description: 省份筛选
   *       - in: query
   *         name: city
   *         schema:
   *           type: string
   *         description: 城市筛选
   *       - in: query
   *         name: isDefault
   *         schema:
   *           type: string
   *           enum: ['0', '1']
   *         description: 是否默认地址筛选
   *     responses:
   *       200:
   *         description: 获取所有用户地址列表成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   type: object
   *                   properties:
   *                     list:
   *                       type: array
   *                       items:
   *                         $ref: '#/components/schemas/UserAddress'
   *                     total:
   *                       type: integer
   *                     page:
   *                       type: integer
   *                     pageSize:
   *                       type: integer
   */
  getAllAddresses = asyncHandler(async (req: Request, res: Response) => {
    // 处理嵌套在params中的查询参数
    const queryParams = (req.query as any).params || req.query;
    
    const params = {
      page: parseInt(queryParams.page as string) || 1,
      pageSize: parseInt(queryParams.pageSize as string) || 10,
      userId: queryParams.userId as string,
      receiverName: queryParams.receiverName as string,
      receiverPhone: queryParams.receiverPhone as string,
      province: queryParams.province as string,
      city: queryParams.city as string,
      isDefault: queryParams.isDefault as string
    };

    const result = await this.userService.getAllAddresses(params);

    return successResponse(res, result, '获取所有用户地址列表成功');
  });
  /**
   * @swagger
   * /users/{id}/addresses:
   *   get:
   *     summary: 获取用户地址列表
   *     tags: [用户地址管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *     responses:
   *       200:
   *         description: 获取用户地址列表成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   type: array
   *                   items:
   *                     $ref: '#/components/schemas/UserAddress'
   */
  getUserAddresses = asyncHandler(async (req: Request, res: Response) => {
    const userId = parseInt(req.params.id);
    
    if (isNaN(userId)) {
      throw new AppError('无效的用户ID', 400);
    }

    const addresses = await this.userService.getUserAddresses(userId);

    return successResponse(res, addresses, '获取用户地址列表成功');
  });

  /**
   * @swagger
   * /users/{id}/addresses:
   *   post:
   *     summary: 创建用户地址
   *     tags: [用户地址管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - receiverName
   *               - receiverPhone
   *               - province
   *               - city
   *               - district
   *               - address
   *             properties:
   *               receiverName:
   *                 type: string
   *                 description: 收货人姓名
   *               receiverPhone:
   *                 type: string
   *                 description: 收货人电话
   *               province:
   *                 type: string
   *                 description: 省份
   *               city:
   *                 type: string
   *                 description: 城市
   *               district:
   *                 type: string
   *                 description: 区县
   *               address:
   *                 type: string
   *                 description: 详细地址
   *               postalCode:
   *                 type: string
   *                 description: 邮政编码
   *               isDefault:
   *                 type: integer
   *                 enum: [0, 1]
   *                 description: 是否默认地址
   *     responses:
   *       201:
   *         description: 用户地址创建成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   $ref: '#/components/schemas/UserAddress'
   */
  createUserAddress = asyncHandler(async (req: Request, res: Response) => {
    const userId = parseInt(req.params.id);
    const addressData: CreateUserAddressRequest = req.body;
    
    if (isNaN(userId)) {
      throw new AppError('无效的用户ID', 400);
    }

    const address = await this.userService.createUserAddress(userId, addressData);

    return successResponse(res, address, '用户地址创建成功', 200);
  });

  /**
   * @swagger
   * /api/users/{id}/addresses/{addressId}:
   *   put:
   *     summary: 更新用户地址
   *     tags: [用户地址管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *       - in: path
   *         name: addressId
   *         required: true
   *         schema:
   *           type: integer
   *         description: 地址ID
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             properties:
   *               receiverName:
   *                 type: string
   *               receiverPhone:
   *                 type: string
   *               province:
   *                 type: string
   *               city:
   *                 type: string
   *               district:
   *                 type: string
   *               address:
   *                 type: string
   *               postalCode:
   *                 type: string
   *               isDefault:
   *                 type: integer
   *                 enum: [0, 1]
   *     responses:
   *       200:
   *         description: 用户地址更新成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   $ref: '#/components/schemas/UserAddress'
   */
  updateUserAddress = asyncHandler(async (req: Request, res: Response) => {
    const userId = parseInt(req.params.id);
    const addressId = parseInt(req.params.addressId);
    const updateData: UpdateUserAddressRequest = req.body;
    
    if (isNaN(userId) || isNaN(addressId)) {
      throw new AppError('无效的用户ID或地址ID', 400);
    }

    const address = await this.userService.updateUserAddress(userId, addressId, updateData);

    return successResponse(res, address, '用户地址更新成功');
  });

  /**
   * @swagger
   * /api/users/{id}/addresses/{addressId}:
   *   delete:
   *     summary: 删除用户地址
   *     tags: [用户地址管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *       - in: path
   *         name: addressId
   *         required: true
   *         schema:
   *           type: integer
   *         description: 地址ID
   *     responses:
   *       200:
   *         description: 用户地址删除成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   */
  deleteUserAddress = asyncHandler(async (req: Request, res: Response) => {
    const userId = parseInt(req.params.id);
    const addressId = parseInt(req.params.addressId);
    
    if (isNaN(userId) || isNaN(addressId)) {
      throw new AppError('无效的用户ID或地址ID', 400);
    }

    await this.userService.deleteUserAddress(userId, addressId);

    return successResponse(res, null, '用户地址删除成功');
  });

  /**
   * @swagger
   * /api/users/{id}/addresses/{addressId}/default:
   *   patch:
   *     summary: 设置默认地址
   *     tags: [用户地址管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *       - in: path
   *         name: addressId
   *         required: true
   *         schema:
   *           type: integer
   *         description: 地址ID
   *     responses:
   *       200:
   *         description: 设置默认地址成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   $ref: '#/components/schemas/UserAddress'
   */
  setDefaultAddress = asyncHandler(async (req: Request, res: Response) => {
    const userId = parseInt(req.params.id);
    const addressId = parseInt(req.params.addressId);
    
    if (isNaN(userId) || isNaN(addressId)) {
      throw new AppError('无效的用户ID或地址ID', 400);
    }

    const address = await this.userService.setDefaultAddress(userId, addressId);

    return successResponse(res, address, '默认地址设置成功');
  });

  /**
   * @swagger
   * /api/users/{id}/avatar:
   *   post:
   *     summary: 上传用户头像
   *     tags: [用户管理]
   *     parameters:
   *       - in: path
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 用户ID
   *     requestBody:
   *       required: true
   *       content:
   *         multipart/form-data:
   *           schema:
   *             type: object
   *             properties:
   *               avatar:
   *                 type: string
   *                 format: binary
   *                 description: 头像文件（支持jpg、png、gif等图片格式，最大5MB）
   *     responses:
   *       200:
   *         description: 头像上传成功
   *         content:
   *           application/json:
   *             schema:
   *               type: object
   *               properties:
   *                 success:
   *                   type: boolean
   *                 message:
   *                   type: string
   *                 data:
   *                   type: object
   *                   properties:
   *                     avatarUrl:
   *                       type: string
   *                       description: 头像URL
   *                     user:
   *                       $ref: '#/components/schemas/User'
   */
  uploadAvatar = asyncHandler(async (req: Request, res: Response) => {
    const id = parseInt(req.params.id);
    
    if (isNaN(id)) {
      throw new AppError('无效的用户ID', 400);
    }

    if (!req.file) {
      throw new AppError('请选择要上传的头像文件', 400);
    }

    // 构建完整的头像URL
    const protocol = req.protocol;
    const host = req.get('host');
    const avatarUrl = `${protocol}://${host}/uploads/avatars/${req.file.filename}`;
    
    const user = await this.userService.updateUser(id, { avatar: avatarUrl });

    return successResponse(res, {
      avatarUrl,
      user
    }, '头像上传成功');
  });
}